package javase.date;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.UnsupportedTemporalTypeException;

public class DateUtilDemo {
    public static final String PATTEN_YMDHMS = "yyyy/MM/dd HH:mm:ss";
    public static final String PATTEN_YMD = "yyyy/MM/dd";
    public static final String PATTEN_HMS = "HH:mm:ss";

    //字符串 转换为 日期型
    public static Object StringToDate(String str){
        DateTimeFormatter dtf ;
        switch (str.length()){
            //年月日时分秒
            case 19:{
                dtf = DateTimeFormatter.ofPattern(PATTEN_YMDHMS);
                LocalDateTime localDateTime = LocalDateTime.parse(str,dtf);
                return localDateTime;
            }
            //年月日
            case 8:{
                dtf = DateTimeFormatter.ofPattern(PATTEN_HMS);
                LocalTime localTime = LocalTime.parse(str,dtf);
                return localTime;

            }
            //时分秒
            case 10:{
                dtf = DateTimeFormatter.ofPattern(PATTEN_YMD);
                LocalDate localDate = LocalDate.parse(str,dtf);
                return localDate;
            }
        }
        return null;
    }

    //日期型 转换为 字符串
    public static String DateToString(Object date){
        DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern(PATTEN_YMDHMS);
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern(PATTEN_YMD);
        DateTimeFormatter dtf3 = DateTimeFormatter.ofPattern(PATTEN_HMS);
        if (date instanceof LocalDateTime){
            LocalDateTime date1 = (LocalDateTime) date;
            return date1.format(dtf1);
        }
        if (date instanceof LocalDate){
            LocalDate date2 = (LocalDate) date;
            return date2.format(dtf2);
        }
        if (date instanceof LocalTime){
            LocalTime date3 = (LocalTime) date;
            return date3.format(dtf3);
        }
        return null;
    }

}

class Test{
    public static void main(String[] args) {
        System.out.println(DateUtilDemo.StringToDate("2021/11/12"));
        System.out.println(DateUtilDemo.StringToDate("15:30:56"));
        System.out.println(DateUtilDemo.StringToDate("2021/11/12 12:30:15"));
        Object o = DateUtilDemo.StringToDate("15:30:56");
        System.out.println(DateUtilDemo.DateToString(o));
    }
}
